/*
 * coneccionAF_UNIX.c
 *
 *  Created on: 29/10/2011
 *      Author: root
 */

#include "includes/conexionAF_UNIX.h"

int32_t serverConexionConsola (char * pathSocket){
	int32_t descSocket,nuevoDesSocket,tamStrucConectado,tamStrucLocal;

	struct sockaddr_un local, conectado;

	if ((descSocket = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
		fprintf(stderr,"error en crear el socket");
		return -1;
	}

	unlink(pathSocket);/*borrar si ya se creo*/

	local.sun_family = AF_UNIX;
	strcpy(local.sun_path, pathSocket);
	tamStrucLocal=strlen(local.sun_path)+sizeof(local.sun_family);
	if (bind(descSocket, (struct sockaddr *)&local,tamStrucLocal) == -1) {
		fprintf(stderr,"error en bind del socket");
		return -1;
	}
	if (listen(descSocket, 2) == -1) {
		fprintf(stderr,"error en listen del socket");
		return -1;
	}

	if ((nuevoDesSocket = accept(descSocket, (struct sockaddr *)&conectado,(size_t *) &tamStrucConectado)) == -1) {
		fprintf(stderr,"error en bind del socket");
		return -1;
	}
	else{
		printf("Por fin PAPA!! nos conectamos y ahora??\n>");
	}
	return nuevoDesSocket;
}


int32_t clienteConexionConsola (char *pathSocket){
	  int32_t descSocket, tamStrucServer;
	  struct sockaddr_un server;

	  if ((descSocket = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
		  fprintf(stderr,"error en crear el socket");
		  return -1;
	  }

	  printf("intentando conectarme a %s\n",pathSocket);

	  server.sun_family = AF_UNIX;
	  strcpy(server.sun_path, pathSocket);
	  tamStrucServer = strlen(server.sun_path) + sizeof(server.sun_family);

	  if (connect(descSocket, (struct sockaddr *)&server, tamStrucServer) == -1) {
		  fprintf(stderr,"error en connect del socket");
	  }

	  printf("me conecte!!!\n");
	  return descSocket;
}

